#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#define ARG_MAX 10
#include <wait.h>
#include <pwd.h>

#define PATH_BIN "/home/stu/quzijie/mydi/test15/mybin/"

char *get_cmd(char *buff,char *myargv[])
{
    if(buff==NULL||myargv==NULL)
    {
        return NULL;
    }
    int i=0;
    char *s=strtok(buff," ");
    while(s!=NULL)
    {
        myargv[i++]=s;
        s=strtok(NULL," ");
    }
    return myargv[0];
}

void run_cmd(char *path,char *myargv[])
{
    if(path==NULL||myargv==NULL)
    {
        return ;
    }
    pid_t pid=fork();
    if(pid==-1)
    {
        return ;
    }
    if(pid==0)
    {
        //子进程
        char pathname[128]={0};

        //路径拼接
        if(strncmp(path,"/",1)==0||strncmp(path,"./",2)==0)
        {
            strcpy(pathname,path);
        }
        else
        {
            strcpy(pathname,PATH_BIN);
            strcat(pathname,path);
        }
        execv(pathname,myargv);
        perror("execv error!\n");
        exit(0);    
        //如果不成功，也能退出（若没有则会进入主函数的while(1)死循环）
    }
    else
    {
        wait(NULL); //防止僵死进程
    }
}

void printf_info()
{
    char *user_str="$"; //普通用户
    int user_id=getuid();
    if(user_id==0)  //管理员
    {
        user_str="#";
    }
    struct passwd *ptr=getpwuid(user_id);
    if(ptr==NULL)
    {
        printf("mybash1.0>>  ");
        fflush(stdout);
        return ;
    }
    char hostname[128]={0};
    if(gethostname(hostname,128)==-1)
    {
        printf("mybash1.0>>  ");
        fflush(stdout);
        return ;

    }
    char dir[256]={0};
    if(getcwd(dir,256)==NULL)
    {
        printf("mybash1.0>>  ");
        fflush(stdout);
        return ;
    }

    printf("\033[1;33m%s@%s\033[0m    \033[1;36m%s\033[0m%s ",ptr->pw_name,hostname,dir,user_str);
    fflush(stdout);
}
int main()
{
    while(1)
    {
        //printf("stu@loalhost:~$ ");
        printf_info();
        fflush(stdout);

        char buff[128];
        fgets(buff,128,stdin);

        char *myargv[ARG_MAX]={0};
        buff[strlen(buff)-1]='\0';

        char *cmd=get_cmd(buff,myargv);

        if(cmd==NULL)
        {
            continue;
        }
        else if(strcmp(cmd,"cd")==0)
        {
            if(myargv[1]!=NULL)
            {
                //报错
                if(chdir(myargv[1])==-1)
                {
                    perror("cd error!\n");
                }
            }
        }
        else if(strcmp(cmd,"exit")==0)
        {
            break;
        }
        else
        {
            //fork+exec
            run_cmd(cmd,myargv);
        }
    }
    exit(0);
}
